package com.framework.service.core.controller;

import com.framework.common.controller.BaseController;
import com.framework.common.domain.WechatMessage;
import com.framework.common.util.WeixinCheckUtil;
import com.framework.common.util.XmlUtil;
import com.framework.service.core.service.IWeixinService;
import com.framework.core.api.response.WxUserOpenIdRes;
import com.framework.service.core.service.IWeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/12 22:53
 * @since JDK 1.8
 */

@RestController
@RequestMapping("/wx")
@Api(value = "WeixinController", description = "微信通用api接口")
@Slf4j
public class WeixinController extends BaseController {

    @Autowired
    private IWeixinService weixinService;

    @ApiOperation(value = "获取微信用户openId", httpMethod = "GET")
    @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    public WxUserOpenIdRes getWeixinOpenidAndKey(@RequestParam("code") String code) {
        return weixinService.getWeixinOpenidAndKey(code);
    }

    @ApiOperation(value = "获取微信用户手机号", httpMethod = "GET")
    @RequestMapping(value = "/getPhoneNumber",method = RequestMethod.GET)
    public String getPhoneNumberFromWeixin(String encryptedData, String sessionKey, String iv) {
        return weixinService.getPhoneNumberFromWeixin(encryptedData, sessionKey, iv);
    }

    /**
     * 微信消息接收和token验证
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/messageHandler",method=RequestMethod.GET)
    public String weChat(HttpServletRequest request, HttpServletResponse response) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        try {
            if (isGet) {
                // 微信加密签名
                String signature = request.getParameter("signature");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");
                // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
                if (StringUtils.isNotBlank(signature) && StringUtils.isNotBlank(nonce) && StringUtils.isNotBlank(timestamp) &&
                        WeixinCheckUtil.checkSignature(signature, timestamp, nonce)) {
                    return echostr;
                }else{
                    return "fail";
                }
            }
        } catch (Exception e) {
            return "fail";
        }
        return "fail";
    }

    @RequestMapping(value="/messageHandler",method=RequestMethod.POST)
    public String  responseEvent(HttpServletRequest req, HttpServletResponse resp)throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String message = "success";
        try {
            //把微信返回的xml信息转义成map
            Map<String, String> map = XmlUtil.xmlToMap(req);
            if(map == null) {
                log.warn("微信消息解析失败");
                return null;
            }
            log.info("接收到微信消息：报文=[{}]", map.toString());
            String fromUserName = map.get("FromUserName");//消息来源用户标识
            String toUserName = map.get("ToUserName");//消息目的用户标识
            String msgType = map.get("MsgType");//消息类型(event或者text)
            String msgId = map.get("MsgId");//消息类型(event或者text)
            String eventType = map.get("Event");//事件类型
            WechatMessage wechatMessage = new WechatMessage();
            wechatMessage.setMsgId(msgId);
            wechatMessage.setFromUserName(fromUserName);
            wechatMessage.setToUserName(toUserName);
            wechatMessage.setEvent(eventType);
            wechatMessage.setMsgType(msgType);

            if(StringUtils.equals("event",msgType)){//如果为事件类型
                if(StringUtils.equals("subscribe", eventType)){//处理订阅事件
                   return weixinService.subscribe(wechatMessage);
                }else if(StringUtils.equals("unsubscribe", eventType)){//处理取消订阅事件
                   // System.out.println("事件类型为:"+eventType);
                   // message = MessageUtil.unsubscribe(toUserName, fromUserName);
                }
            }else {
//                //微信消息分为事件推送消息和普通消息,非事件即为普通消息类型
//                switch (msgType) {
//                    case "text":{//文本消息
//                        String content = map.get("Content");//用户发的消息内容
//                        content = "您发的消息内容是:"+content+",如需帮助,请联系郭先生,18629374628";
//                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
//                        break;
//                    }
//                    case "image":{//图片消息
//                        String content = "您发的消息内容是图片,如需帮助,请联系郭先生,18629374628";
//                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
//                        break;
//                    }
//                    default:{//其他类型的普通消息
//                        break;
//                    }
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

//    public static String getUserNickName(String openId) {
//        String nickName  = null;
//        try {
//            Map map = WeiXinUtil.cacheTokenAndTicket();
//            String token = (String)map.get("access_token");
//            String url = URL.replace("OPENID", openId).replace("ACCESS_TOKEN", token);
//            JSONObject obj = WeiXinUtil.HttpGet(url);
//            nickName = (String)obj.get("nickname");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return nickName;
//    }

}
